<?php

class type_image{
	
	public $id;

	protected $old;
	
	protected static $max_size = 1048576;
	protected static $mime_types = array (
                                   'image/gif',
                                   'image/jpeg',
                                   'image/png'
                                   );
	protected static $max_thumbnail_dim = array ('width'=>'300','height'=>'250');
	protected static $img_rs = false;
	protected static $img_dim = false;
	protected static $img_func = false;
	
	/**
	 * Constructor
	 * 
	 * @author	Armin Borumand
	 */
	function __construct(){
		global $lb;
		
		$this->id    = $lb['page']->type_id;
		$this->title = $this->get_title();
	}

	/**
	 * generate and return title of page
	 * 
	 * @author	Armin Borumand
	 * @return 	string		page's title on success or false on failure
	 */
	function get_title($id=false){
		global $lb;
		
		if($id === false){
			$id = $this->id;
		}
		
		$query = 'SELECT title FROM #__type_image WHERE id=#';
		
		$params = array (
				array ($id, 'int')
				);
			
		$result = $lb['db']->query($query, $params);
		
		// if page exist
		if($result['num_of_rows'] > 0){
			return $result['rows'][0]['title'];
		}else{
			return false;
		}
	}
	
	/**
	 * generate and return content of page
	 * 
	 * @author	Armin Borumand
	 * @param 	boolean		if current user can write this page, it will be true
	 * @return 	string		page's content
	 */
	function get_content($freez=true){
		global $lb;
		
		$query  = 'SELECT `desc` FROM #__type_image WHERE id = #';
		$params = array (
				array ($this->id, 'int')
				);
		$result = $lb['db']->query($query, $params);
		
		// if page exist
		if($result['num_of_rows'] > 0){
			if($freez){
				$out['image'] = $this->id;
				$out['desc']  = lb_page::wikicode($result['rows'][0]['desc']);
			}else{
				$out = stripslashes($result['rows'][0]['desc']);
			}
			return $out;
		}else{
			return false;
		}
	}

	/**
	 * Add a new page
	 *
	 * @author	Armin Borumand
	 * @param	array		title=> page title,
	 *				desc=> image description
	 *				image=> name=> image name
	 *				image=> size=> size of image
	 *				image=> tmp_name=> image path
 	 *				image=> type=> mime type,
	 * @param	boolean	page id
	 * @return 	int	added page id
	 */
	function add_page(&$arr, $id=false){
		global $lb;
		
		if(!self::is_valid($arr['image']['type'], $arr['image']['size'])){
			return false;
		}
		$arr['desc'] = type_image::html_filter($arr['desc']);
		
		$query  = 'INSERT INTO #__type_image ';
		$params = array (
				array ($arr['title']	 	, 'text'),
				array ($arr['image']['type']	, 'text'),
				array ($arr['image']['size']	, 'int'),
				array ($arr['desc']		, 'text')
				);
		if(!$id){
			$query .= '(title, mime_type, size, `desc`) VALUES (#, #, #, #)';
		}else{
			$query .= '(id, title, mime_type, size, `desc`) VALUES (#, #, #, #, #)';
			$params = array_unshift($params, array ($id, 'int'));
		}
		
		$result = $lb['db']->query($query, $params);
		
		if($result['result']){
			$page_id   = $result['insert_id'];
			$back_queries  = array (
						'DELETE FROM #__type_image WHERE id = #'
						);	
			$back_params = array (
					array (
						array ($page_id, 'int')
						)
					);
					
			self::imagecreate($arr['image']['tmp_name'], $arr['image']['type']);
			$content   = file_get_contents($arr['image']['tmp_name']);
			$thumbnail = self::get_thumbnail_contents();
			self::imagedestroy();
			$queries = array (
					'INSERT INTO #__type_image_store (id, content) VALUES (#, #)',
					'INSERT INTO #__type_image_thumbnail (id, size, content) VALUES (#, #, #)'
					);
			array_push($back_queries ,
						'DELETE FROM #__type_image_store WHERE id = #',
						'DELETE FROM #__type_image_thumbnail WHERE id = #'
				);
								
			$params	= array (
					array (
						array ($page_id, 'int'),
						array ($content, 'blob')
					),
					array (
						array ($page_id			, 'int'),
						array ($thumbnail['size']	, 'int'),
						array ($thumbnail['content']	, 'blob')
					)
				);
			array_push($back_params ,
						array (
							array ($page_id, 'int'),
							array ($content, 'blob')
						),
						array (
							array ($page_id			, 'int'),
							array ($thumbnail['size']	, 'int'),
							array ($thumbnail['content']	, 'blob')
						)
				);			
			
			$i = 0;
			foreach($queries as $query){
				$result[] = $lb['db']->query($query, $params[$i++]);
			}
			
			if($result[0]['result'] && $result[1]['result']){
				@unlink($arr['image']['tmp_name']);
				return $page_id;
			}else{
				$i = 0;
				foreach($back_queries as $back_query){
					$lb['db']->query($back_query, $back_params[$i++]);
				}
				return false;
			}
			
		}else{
			return false;
		}
	}
	
	/**
	 * update edited page information in database
	 * 
	 * @author	Armin Borumand
	 * @param	array		title=> page title,
	 *				desc=> image description
	 *				image=> name=> image name
	 *				image=> size=> size of image
	 *				image=> tmp_name=> image path
	 *				image=> type=> mime type,
	 * @param	boolean	store old values
	 * @return 	boolean	true on success or false on failure
	 */
	function edit_page(&$arr, $backup=true){
		global $lb;
		
		$id = $this->id;
		$arr['desc'] = type_image::html_filter($arr['desc']);
		
		if($backup){
			$this->old['title']	= $this->title;
			$this->old['desc']	= $this->get_content(false);
		}
				
		if($arr['image']['tmp_name'] != '' && self::is_valid($arr['image']['type'], $arr['image']['size']) ){
			if($backup){
				$this->old['image']	= $this->image($this->id);
				$this->old['thumbnail'] = $this->image($this->id, true);
			}
			
			self::imagecreate($arr['image']['tmp_name'], $arr['image']['type']);
			$content   = file_get_contents($arr['image']['tmp_name']);
			$thumbnail = self::get_thumbnail_contents();
			self::imagedestroy();
			
			$query = 'UPDATE #__type_image AS A, #__type_image_store AS B, #__type_image_thumbnail AS C  
					SET 
					A.title=#,
					A.desc=#, 
					A.mime_type = #, 
					A.size = #, 
					B.content = #,
					C.size = #,
					C.content = #
				  WHERE A.id= # AND B.id = # AND C.id = #';
			$params = array ( 
					array ($arr['title']		, 'text'),
					array ($arr['desc'] 		, 'text'),
					array ($arr['image']['type']	, 'text'),
					array ($arr['image']['size']	, 'int'),
					array ($content			, 'blob'),
					array ($thumbnail['size']	, 'int'),
					array ($thumbnail['content']	, 'blob'),
					array ($id			, 'int'),
					array ($id			, 'int'),
					array ($id			, 'int')
					);
			
			@unlink($arr['image']['tmp_name']);
		}else{
			$query = 'UPDATE #__type_image SET `title`= #, `desc` = # WHERE `id` = #';
			$params = array (
					array ($arr['title'], 'text'),
					array ($arr['desc'] , 'text'),
					array ($id, 'int')		
					);
		}
		
		$result = $lb['db']->query($query, $params);
			
		if($result['num_of_rows'] > 0){
			$this->title = $arr['title'];
			return $id;
		}
		
		return false;
	}
		
	/**
	 * Remove page
	 *
	 * @author	Armin Borumand
	 * @param	int		page type id to be removed (if false remove current page)	
	 * @return	boolean	true on success and false on failure
	 */
	function remove_page($id = false){
		global $lb;
		
		if(!$id){
			$id = $this->id;
		}
		
		$query = 'DELETE A,B,C 
			  FROM #__type_image AS A, #__type_image_store AS B, #__type_image_thumbnail AS C
			  WHERE A.id = # AND B.id = # AND C.id = #';
		$params = array (
				array ($id, 'int'),
				array ($id, 'int'),            
				array ($id, 'int')
				);
		$result = $lb['db']->query($query, $params);

		
		return $result['result'];
	}	

	/**
	 * Restore old title and content in plugin database
	 *
	 * @author	Armin borumand
	 * @param	boolean	Add or edit
	 * @return	boolean	true on success and false on failure
	 */
	function restore($add=false){
		global $lb;
		
		if(!isset($this->old['title'])){
			return false;
		}
		
		if($add === false){
			$result = $this->edit_page($this->old, false);
		}else{
			$result = $this->add_page($this->old, $this->id);
		}
		
		if($result){
			$arr['title'] = $this->old['title'];
			$this->old = array ();
			return true;
		}else{
			return false;
		}
		
	}
	/**
	  * install this page type
	  * 
	  * @author	Armin Borumand
	  * @return	boolean		return true if successfull installed
	  */
	function install(){
		global $lb;
		
		$queries = array (
			'CREATE TABLE `#__type_image` (
			  `id` int(11) NOT NULL auto_increment,
			  `title` varchar(255) NOT NULL default \'\',
			  `mime_type` varchar(60) NOT NULL default \'\',
			  `size` int(11) NOT NULL default \'0\',
			  `width` smallint(5) NOT NULL default \'0\',
			  `height` smallint(5) NOT NULL default \'0\',
			  `desc` text NOT NULL,
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1'
			,
			'CREATE TABLE `#__type_image_store` (
			  `id` int(11) NOT NULL default \'0\',
			  `content` longblob NOT NULL,
			   KEY `id` (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=latin1'
			,
			'CREATE TABLE `#__type_image_thumbnail` (
			  `id` int(11) NOT NULL default \'0\',
			  `size` int(10) NOT NULL default \'0\',
			  `content` mediumblob NOT NULL,
			  KEY `id` (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=latin1'
			);
		
		foreach($queries as $query){
			$result[] = $lb['db']->query($query, array ());
		}
		return $result[0]['result'] && $result[1]['result']  && $result[2]['result'];
	}
	
	/**
	  * uninstall this page type
	  * 
	  * @author	Armin Borumand
	  * @return	boolean		return true if successfull uninstalled
	  */
	function uninstall(){
		global $lb;
		
		$queries = array (
					'DROP TABLE `#__type_image`',
					'DROP TABLE `#__type_image_store`'
				);
		
		foreach($queris as $query){
			$result[] = $lb['db']->query($query, array ());
		}
		return $result[0]['result'] && $result[1]['result'];
	}
	
	/**
	 * search in pages
	 *
	 * @author	Armin Borumand
	 * @param	array		search words
	 * @param	int		limit start row
	 * @param	int		number of results
	 * @return	array		consist of page title and ids
	 */
	function search(&$arr, $start, $number){
		global $lb;
		
		$conds = '';
		foreach($arr as $val){
			$params[] = array ('%'.$val[1].'%', 'text');
			$conds .= 'CONCAT(`title`, `desc`) like # '.$val[0].' ';
		}			
		$conds = substr($conds, 0, strlen($conds)-3);
			
		//Setting LIMIT ranges
		$params[] = array ($start,	'int');
		$params[] = array ($number,	'int');
		
		//double use!
		$params = array_merge($params, $params);
		array_pop($params);
		array_pop($params);
		
		$result = $lb['db']->query('SELECT id ,title 
						FROM #__type_image 
						WHERE ' . $conds . 'LIMIT #,# 
						UNION SELECT count(id), NULL
						FROM #__type_image 
						WHERE ' . $conds, $params);
		if($result['num_of_rows'] < 1){
			$result['rows'] = array ();
		}
		
		$num = $result['num_of_rows'] -1 ;
		if($num < $number){
			$number = $num;
		}
		
		$result['num_of_rows'] = intval($result['rows'][$number]['id']);
		array_pop($result['rows']);			
			
		if($num == 0){
			return $result;
		}
			
		for($i = 0; $i < $num; $i++){
			$image_ids[] = $result['rows'][$i]['id'];
		}
			
		$page_ids = lb_page::get_id($image_ids, 'image');
						
		for($i = 0; $i < $num; $i++){
			$result['rows'][$i]['id'] = $page_ids[$image_ids[$i]];
		}	

		return $result;
	}

	/**
	 * Return number of pages
	 *
	 * @author	Armin Borumand
	 * @return	int	number of pages
	 */
	function count(){
		global $lb;
		
		$result = $lb['db']->query('SELECT count(*) AS count FROM #__type_image', array ());
		
		if($result['num_of_rows'] > 0){
			return $result['rows'][0]['count'];
		}else{
			return -1;
		}		
	}
	
	/**
	 * Return image mime type and content
	 *
	 * @access	public
	 * @auhtor	Armin Borumand
	 * @param	int	image id
	 * @param	bool	thumbnail or not
	 * @return	array	mime type and content
	 */
	function image($id, $thumbnail=false){
		global $lb;
		
		if($thumbnail){
			$query = 'SELECT A.mime_type, B.size, B.content 
						FROM #__type_image AS A ,#__type_image_thumbnail AS B
						WHERE A.id = # AND B.id = #';			
		}else{
			$query = 'SELECT A.mime_type, A.size, B.content 
						FROM #__type_image AS A ,#__type_image_store AS B
						WHERE A.id = # AND B.id = #';
		}
		
		$params = array (
				array ($id, 'int'),
				array ($id, 'int')
				);
		$result = $lb['db']->query($query, $params);
		if($result['num_of_rows'] > 0){
			return $result['rows'][0];
		}else{
			return false;
		}
	}
	
	/**
	 * Check image params
	 * 
	 * @access	protected
	 * @author	Armin Borumand
	 * @param	string	image mime type
	 * @param	int		image size
	 * @return	boolean	true if valid and false if not
	 */
	function is_valid($type, $size){
		if($size > 0 && $size < self::$max_size && in_array ($type, self::$mime_types)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * Create image resource
	 *
	 * @access	protected
	 * @author	Armin Borumand
	 * @param	string	image path
	 * @param	string	image type
	 */
	function imagecreate($path, $type){
		switch($type){
			case 'image/gif':
				self::$img_rs = imagecreatefromgif($path);
				self::$img_func = 'imagegif';
				break;
				
			case 'image/jpeg':
				self::$img_rs = imagecreatefromjpeg($path);
				self::$img_func = 'imagejpeg';
				break;
				
			case 'image/png':
				self::$img_rs = imagecreatefrompng($path);
				self::$img_func = 'imagepng';
				break;
			default:
				return;
		}
		self::$img_dim = array (
				'width' => imagesx(self::$img_rs),
				'height'=> imagesy(self::$img_rs)
				);
	}
	
	/**
	 * Destroy image resource and details
	 *
	 * @access	protected
	 */
	function imagedestroy(){
		@imagedestroy(self::$img_rs);
		self::$img_rs = false;
		self::$img_dim = false;
		self::$img_func = false;
	}
	
	/**
	 * Retrun thumbnail content and size
	 *
	 * @access	protected
	 * @author	Armin Borumand
	 * @param	int	thumbnail width
	 * @param	int	thumbnail height
	 * @return	array	thumbnail content and size
	 */
	function get_thumbnail_contents($width=false, $height=false){
		global $lb;
		
		if($height == false){
			$thumbnail_dim = self::thumbnail_dim(self::$img_dim['width'], self::$img_dim['height']);
		}else{
			$thumbnail_dim = array (
						'width' => $width,
						'height'=> $height
						);
		}
		$create_thumbnail = self::$img_func;
		
		$thumbnail_rs  = imagecreatetruecolor($thumbnail_dim['width'], $thumbnail_dim['height']);
		imagecopyresized($thumbnail_rs, self::$img_rs, 0, 0, 0, 0
						 , $thumbnail_dim['width'], $thumbnail_dim['height']
						 , self::$img_dim['width'], self::$img_dim['height']);
		$tmp_file = tempnam('/tmp', 'lb');
		$create_thumbnail($thumbnail_rs, $tmp_file);
		imagedestroy($thumbnail_rs);
		
		return array ('content'	=>file_get_contents($tmp_file),
				'size'	=>filesize($tmp_file));
	}
	
	/**
	 * Calculate thumbnail dimensions
	 *
	 * @access	protected
	 * @author	Armin Borumand
	 * @param	int	image width
	 * @param	int	image height
	 * @return	array	thumbnail dimensions
	 */
	function thumbnail_dim($width, $height){
		$scale = 1;
		
		if($width > self::$max_thumbnail_dim['width']){
			$scale = $width / self::$max_thumbnail_dim['width'];
		}
		
		if(($tmp_scale =  $height / self::$max_thumbnail_dim['height']) > $scale){
			$scale = $tmp_scale;
		}
		
		$result['width']  = floor($width / $scale);
		$result['height'] = floor($height / $scale);
		
		return $result;
	}
	
	/**
	 * Filter input text from html tags
	 *
	 * @access	protected
	 * @param	string	input text
	 * @param	string	clean text
	 */
	function html_filter($string){
		//html allowable tags
		$allowable = array('<br>', '<a>', '<p>', '<div>', '<b>', '<strike>', '<u>', '<em>', '<strong>'
						 , '<blockquote>', '<sup>', '<sub>', '<ul>', '<ol>', '<li>',);
		return lb_system::strip_tags($string, $allowable);
	}
}
